package com.wudl.govern.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

/**
 * @author ：wudl
 * @date ：Created in 2022-04-05 21:14
 * @description：
 * @modified By：
 * @version: 1.0
 */

@Component
public class RestTemplateUtils {
    /**
     * post请求
     *
     * @param restTemplate
     * @param url          地址
     * @param params       字符串参数
     * @return
     */
    public static <T> T postHttp(RestTemplate restTemplate, String url, String params, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(params, headers);

        return restTemplate.postForObject(url,
                formEntity, clazz);
    }

    /**
     * get带参请求
     *
     * @param restTemplate
     * @param url
     * @param uriVariableValues 可变参数
     * @return
     */
    public static <T> T getHttp(RestTemplate restTemplate, String url, Class<T> clazz, Object... uriVariableValues) {
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build().expand(uriVariableValues).encode();
        URI uri = uriComponents.toUri();
        return restTemplate.getForObject(uri, clazz);
    }

    /**
     * get无参请求
     *
     * @param restTemplate
     * @param url
     * @return
     */
    public static <T> T getHttp(RestTemplate restTemplate, String url, Class<T> clazz) {
        return restTemplate.getForObject(url, clazz);
    }

}
